package code.excel.poi;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * <p></p>
 *
 * @version 1.0
 * @author:huangwf
 * @date:2017/8/21 13:57
 * @history
 */

public class WriteToFile {

    public final static String HTML_ATTR = "HTMLATTR";
    public final static String HTML_TEXT = "HTMLTEXT";

    /**
     * <p>数据写入Excel</p>
     *
     * @author:huangwf
     * @date:2017/8/18 13:56
     * @version 1.0
     * @history
     */
    public static void wirteToExcel(String filePathName, List<Map<String, Object>> list, String sheetName) throws IOException, InvalidFormatException {
        File file = new File(filePathName);
        HSSFWorkbook workbook;
        HSSFSheet sheet;
        InputStream is = null;
        if (!file.exists()) {
            workbook = new HSSFWorkbook();
            if (sheetName != null && "".equals(sheetName)) {
                sheet = workbook.createSheet(sheetName);
            } else {
                sheet = workbook.createSheet("sheet1");
            }
        } else {
            is = new FileInputStream(file);
            workbook = (HSSFWorkbook) WorkbookFactory.create(is);
            sheet = workbook.getSheetAt(0);
        }
        sheet.setColumnWidth(0, 25 * 256);
        sheet.setColumnWidth(1, 25 * 256);

        int lastRowNumber = sheet.getPhysicalNumberOfRows();
        Row curRow = null;
        for (Map<String, Object> item : list) {
            curRow = sheet.createRow(lastRowNumber);
            curRow.createCell(0).setCellValue(item.get(HTML_TEXT).toString());
            curRow.createCell(1).setCellValue(item.get(HTML_ATTR).toString());
            ++lastRowNumber;
        }
        OutputStream os = new FileOutputStream(file);
        workbook.write(os);
        os.close();
        if (is != null) {
            is.close();
        }
    }

    /**
     * <p>更新写入Txt文本</p>
     *
     * @author:huangwf
     * @date:2017/8/21 14:05
     * @version 1.0
     * @history
     */
    public static void witeToText(String str, String filePathName) {
        try {
            File file = new File(filePathName);
            BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
            output.write(str);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
